import React from 'react'
import {
  Route,
  Redirect,
  withRouter,
} from 'react-router-dom'
import {
  inject,
  observer,
} from 'mobx-react'
import PropTypes from 'prop-types'

import TopicList from '../views/topic-list'
import TopicDetail from '../views/topic-detail'
import Login from '../views/user/login'
import UserInfo from '../views/user/info'
import TopicCreate from '../views/topic-create'
import TestApi from '../views/test/api.test'

const PrivateRouter = ({ isLogin, component: Component, ...rest }) => (
  <Route
    {...rest}
    render={
      props => (
        isLogin
          ? <Component {...props} />
          : (
            <Redirect
              to={{
                pathname: '/login',
                search: `?from=${rest.path}`,
              }}
            />
          )
      )
    }
  />
)

const InjectedPrivateRouter = withRouter(inject(({ appState }) => {
  return {
    isLogin: appState.user.isLogin,
  }
})(observer(PrivateRouter)))

PrivateRouter.propTypes = {
  isLogin: PropTypes.bool,
  Component: PropTypes.element.isRequired,
}
PrivateRouter.defaultProps = {
  isLogin: false,
}

export default () => [
  <Route path="/" render={() => <Redirect to="/list" />} exact key="root" />,
  <Route path="/list" component={TopicList} key="list" />,
  <Route path="/detail/:id" component={TopicDetail} key="detail" />,
  <Route path="/test" component={TestApi} key="test" />,
  <Route path="/login" component={Login} key="login" />,
  <InjectedPrivateRouter path="/user/info" component={UserInfo} key="user-info" />,
  <InjectedPrivateRouter path="/topic/create" component={TopicCreate} key="topic-create" />,
]
